package com.nifostasky.utils;

import android.util.ArrayMap;

import com.nifostasky.entity.ComicInfo;
import com.nifostasky.entity.SearchInfo;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;


import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 解析网页,获取网页内容
 * 图片 总页数 总章节
 */
public class JsoupContent {
    //维持一个comic的引用
    private ComicInfo comicinfo = null;
    //需要爬取的网站
    private String url = null;
    //网站的页面内容
    private Document document = null;
    //判断是否获取成功
    private boolean flag = false;


    //构造
    public JsoupContent() {
        this.comicinfo = new ComicInfo();
    }



    public JsoupContent(String url) {
        this.comicinfo = new ComicInfo();
        this.url = url;
    }


    public boolean isFlag() {
        return flag;
    }

    public void setFlag(boolean flag) {
        this.flag = flag;
    }

    public ComicInfo getComicinfo() {
        return comicinfo;
    }

    public void setComicinfo(ComicInfo comicinfo) {
        this.comicinfo = comicinfo;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    //维持某一个网站的的连接
    private void setDocument(){
        //解析网页 建立网站的连接   获取网页的页面对象
        try {
            document = Jsoup.connect(url).
                    userAgent("Mozilla/5.0 (Windows NT 6.1; rv:30.0) Gecko/20100101 Firefox/30.0").
                    get();
//            document = Jsoup.parse(new URL(url),300000);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    //获取某一章节的图片名(通过url地址来获取)  和该章节页数
    public void setPictureName() {
        //访问网页  获取页面对象
        this.setDocument();



        //script数组
        if (document !=null) {
            Elements src1 = document.select("script");//获取第二个script对象
            if(src1!=null && src1.size()>=2){
                Elements src = src1.eq(2);
            if(src != null) {
                // System.out.println(src);
                //System.out.println("==============================================================");

                //js变量数组
                String[] jpg = src.get(0).data().toString().split("var");
                if (jpg != null) {
                    //取的单个js变量
                    for (String var : jpg) {
                        //过滤var为空的数据
                        if (var.contains("=")) {
                            //取到满足条件的js变量
                            if (var.contains("chapterImages")) {

                                //System.out.println(var);

                                //将var字符串分离 变成变量
                                String[] kvp = var.split("=");
                                //将图片名转换为字符串数组
                                String[] v = kvp[1].trim().substring(2, kvp[1].trim().length() - 3).split("\",\"");
                                //取地js变量并存入map中
                                //                   System.out.println(kvp[0].trim());
/*
                    for (String v1 : v)
                        System.out.println(v1);
*/

                                //将图片名数组保存到漫画信息中
                                comicinfo.setPictureName(v);
                            }
                            //
                            if (var.contains("chapterPath")) {
                                String chapter[] = var.split("=");
                                String chapterPath = chapter[1].trim().substring(1, chapter[1].length() - 3).trim();
                                this.comicinfo.setUrlBefor(chapterPath);
/*
                    System.out.println("------------------------------------------------------------------------------");
                    System.out.println(chapterPath);
                    System.out.println("------------------------------------------------------------------------------");
*/
                            }
                            if (var.contains("pageImage")) {
                                String chapter[] = var.split("=");
                                String chapterPath = chapter[1].trim().substring(1, chapter[1].indexOf("images") - 1).trim();
                                this.comicinfo.setUrlAgo(chapterPath);
    /*                System.out.println("------------------------------------------------------------------------------");
                    System.out.println(chapterPath);
                    System.out.println("------------------------------------------------------------------------------");
*/
                            }
                        }
                    }
                    //获取数据成功 设置标志
                    flag = true;
                }else {
                    flag =false;
                }

                } else {
                    flag = false;
                }
            } else {
                flag = false;
            }
        }else{
            flag = false;
        }
    }









    /**
     * 获取所有的章节链接
     */
    public void setChapterName() {
        this.setDocument();


        List<String[]> list = new ArrayList<>();


        if (document != null) {
            /*                  获取封面图和漫画名              */
            Elements surfacePlots = document.getElementsByClass("page-main");
            if (surfacePlots != null && surfacePlots.size() != 0) {
                Elements surfacePlotScripts = surfacePlots.get(0).getElementsByTag("script");
                String surfacePlot[] = surfacePlotScripts.get(0).toString().split("var");

                for (String surface : surfacePlot) {
                    if (surface.contains("=")) {
                        //如果是图片
                        if (surface.contains("pageImage")) {
                            String srcs[] = surface.split("=");

                            String src = srcs[1].trim().substring(1, srcs[1].trim().length() - 2).trim();
                            //将图片添加进漫画信息中
                            this.comicinfo.setSurfacePlotUrl(src);
                        }
                        //获取漫画名
                        if (surface.contains("pageTitle")) {
                            String titles[] = surface.split("=");
                            String title1 = titles[1];
                            if (title1.contains("_")) {
                                String title = title1.substring(2, title1.indexOf("_")).trim();
                                //添加进漫画名中
                                this.comicinfo.setComicName(title);
                            }
                        }
                    }

/*                 System.out.println(imgs);
                 //封面图路径
                System.out.println(imgs.get(0));
                 String src = imgs.get(0).getElementsByAttribute("src").text().trim();
                 String alt = imgs.get(0).getElementsByAttribute("alt").text();
                 System.out.println(src+"\n"+alt);
                 //将图片和漫画名添加进漫画信息中
                this.comicinfo.setSurfacePlotUrl(src);
                this.comicinfo.setComicName(alt);*/
                }



            /* Elements titles = document.select("title");
            if(titles != null&&titles.size()!=0) {
                String title1 = titles.eq(0).text();
                if(title1.contains("_")) {
                    String title = title1.substring(0, title1.indexOf("_")).trim();
                    //添加进漫画名中
                    this.comicinfo.setComicName(title);
                }

            }*/




                /*                 获取漫画官网  officialWebsiteUrl                 */
                Elements script1 = document.select("script");
                if (script1 != null && script1.size() >= 2) {
                    Elements script = script1.eq(2);//获取第二个script对象
                    if (script != null) {

                        //System.out.println(script);
                        String[] strings = script.get(0).toString().split("var");
                        if (strings != null) {

                            for (String string : strings) {
                                if (string.contains("=")) {
                                    if (string.contains("siteUrl")) {
                                        String split[] = string.split("=");
                                        this.comicinfo.setOfficialWebsiteUrl(split[1].trim().substring(1, split[1].length() - 12).trim());
                                    }
                                }
                            }
                        }
                    }
                }


                /*           获取漫画章节                     */
                //#chapter-list-54 > li:nth-child(1) > a
                Elements elements1 = document.getElementsByClass("chapter-body");
                if (elements1 != null && elements1.size() != 0) {
                    //System.out.println(element);
                    Elements elements = elements1.get(0).getElementsByTag("li");
                    if (elements != null) {
                        //将获取漫画名和漫画对应的地址
                        for (Element element1 : elements) {
                            String chapter[] = new String[2];
                            String urlname = element1.getElementsByTag("a").eq(0).attr("href");
                            String name = element1.getElementsByTag("span").get(0).text();
                            //System.out.println(name+" : "+urlname);
                            chapter[0] = name.trim();
                            chapter[1] = urlname.trim();
                            list.add(chapter);
                        }
                        //添加到漫画信息中
                        this.comicinfo.setChapterName(list);
                        //获取数据成功 设置标志
                        flag = true;
                    } else {
                        flag = false;
                    }


                } else {
                    flag = false;
                }
            } else {
                flag = false;
            }
        }
    }



    public List<SearchInfo> setSearchInfo(String search){
        List<SearchInfo> list = new ArrayList<>();
        String url1 = "https://www.gufengmh8.com/search/?keywords="+search;
        //String url1 = "https://www.gufengmh8.com/search/?keywords=yes";
        Document document =null;
        /********************链接服务器,获取页面对象*********************************/
        try {
            document = Jsoup.connect(url1).
                    userAgent("Mozilla/5.0 (Windows NT 6.1; rv:30.0) Gecko/20100101 Firefox/30.0").
                    get();
        } catch (IOException e) {
            return null;
        }
        /*****************获取搜索数据***********************/
        //获取需要的html内容   #contList
        Element elements = document.getElementById("contList");
        if(elements != null) {
            //获取li标签
            Elements lis = elements.getElementsByTag("li");
            if (lis != null) {
                //获取li标签中需要的内容  封面图 漫画名  漫画地址
                for (Element li : lis) {
                    //获取漫画地址
                    String comicAdress = li.getElementsByTag("a").get(0).attr("href").trim();
                    //获取漫画名
                    String comicName = li.getElementsByTag("a").get(0).attr("title").trim();
                    //获取漫画图片地址
                    String pictureAdress = li.getElementsByTag("img").get(0).attr("src").trim();
                    //加入到list集合中
                    //System.out.println(comicAdress + "\n" + comicName + "\n" + pictureAdress + "\n");
                    list.add(new SearchInfo(comicAdress, comicName, pictureAdress));
                }
                return list;
            }else{
                return null;
            }
        }else{
            return null;
        }
    }















        public static boolean isValid(String strLink){
            URL url = null;
            try{
                url = new URL(strLink);
                InputStream in = url.openStream();
                return true;
            } catch (Exception e){
                return false;
            }
        }

    //判断一个链接是否有效
  /*  public static boolean isValid(String strLink){
        URL url =null;
        try{
            url = new URL(strLink);
            HttpURLConnection connt = (HttpURLConnection) url.openConnection();
            connt.setRequestMethod("HEAD");
            String strMessage = connt.getResponseMessage();
            if(strMessage.compareTo("Not Found")==0){
                return false;
            }

        } catch (Exception e){
            return false;
        }
        return true;
    }*/





/*
            URL url;  
             
                    try {  
 
            url = new URL("http://www.baidu.com");  
 
            InputStream in = url.openStream();  
 
            System.out.println("连接可用");  
 
      } catch (Exception e1) {  
 
            System.out.println("连接打不开!");  
 
            url = null;  
 
       }  
             
               }  
*/

          /* public static boolean isValid(String strLink){
            　　URL url;
            　　try {
            　　url = new URL(strLink);
            　　HttpURLConnection connt = (HttpURLConnection)url.openConnection();
            　　connt.setRequestMethod("HEAD");
            　　String strMessage = connt.getResponseMessage();
            　　if (strMessage.compareTo("Not Found") == 0) {
            　　return false;
            　　}
            　　connt.disconnect();
            　　} catch (Exception e) {
            　　return false;
            　　}
            　　return true;
　　      }
    */









    public static void main(String[] args){

        JsoupContent content = new JsoupContent("https://www.gufengmh8.com/manhua/xugoutuili/50220.html");

/*
        for(SearchInfo searchInfo : content.setSearchInfo("辉夜")){
            System.out.println(searchInfo.getComicNmae()+"\n"
                    +searchInfo.getComicAdress()+"\n"
                    +searchInfo.getPictureAdress()
            );
        }

*/

//https://www.gufengmh8.com/manhua/wujijiadeliaoliren/
        content.setUrl("https://www.gufengmh8.com/manhua/wujijiadeliaoliren/");
        System.out.println(JsoupContent.isValid(" https://jingyan.baidu.com/article/4e5b3e1999aa4fd1901e248f.html"));
        //System.out.println(JsoupContent.isValid("asdfasfdasdfa"));

        content.setChapterName();
        System.out.println(content.comicinfo.getSurfacePlotUrl()+"\n"+content.getComicinfo().getComicName());
        System.out.println(content.isFlag());
        for(String[] list :content.getComicinfo().getChapterName()){
            System.out.println(list[0]+" : "+ list[1]);
        }
        System.out.println(content.getComicinfo().getOfficialWebsiteUrl());
        System.out.println(content.getComicinfo().getComicName());



        content.setUrl(content.getComicinfo().getOfficialWebsiteUrl()+
                content.getComicinfo().getChapterName().get(2)[1]);

        content.setPictureName();
        //输出页数和图片名
        for(String picturename:content.getComicinfo().getPictureName()){
            System.out.println(picturename);
        }

        System.out.println("页数:"+ content.getComicinfo().getPageNumber());
        System.out.println("网址 "+ content.getComicinfo().getUrlAgo()+content.getComicinfo().getUrlBefor());








          /*      //测试,获取网页内容
                //需要获取的网页地址
                String url = "https://www.gufengmh8.com/manhua/xugoutuili/50220.html#p=1";
                //设置一个js 页面对象
                Document document = null;
                //解析网页
                try {
                    document = Jsoup.connect(url).
                            userAgent("Mozilla/5.0 (Windows NT 6.1; rv:30.0) Gecko/20100101 Firefox/30.0").
                            get();
        //            document = Jsoup.parse(new URL(url),300000);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //所有js中能用的里面都能用
                //获取总页数和当前页数

                //script数组
                Elements src = document.select("script").eq(2);//获取第二个script对象
                System.out.println(src);
                System.out.println("==============================================================");
                //js变量数组
                String[] jpg = src.get(0).data().toString().split("var");

                //取的单个js变量
                for(String var :jpg){
                    //过滤var为空的数据
                    if(var.contains("=")){
                        //取到满足条件的js变量
                        if(var.contains("chapterImages")){

                            System.out.println(var);

                            //将var字符串分离 变成变量
                            String[] kvp  = var.split("=");
                            String[] v = kvp[1].trim().substring(2, kvp[1].trim().length()-3).split("\",\"");
                            //取地js变量并存入map中
                            System.out.println(kvp[0].trim());
                            for(String v1 : v)
                            System.out.println(v1);

                        }
                    }
                }






                System.out.println("==============================================================");
        */



                /*

                Elements page = document.getElementsByClass("chapter-view");
                Element img = document.getElementById("tbCenter");
                System.out.println(page.html());
                System.out.println("===========a===================================================");
                System.out.println(img.html());
                System.out.println("==============================================================");
                //获取img标签
                Elements elemnts = img.getElementsByTag("img");
                for (Element elements: elemnts){
                    System.out.println(elemnts.html());
                }
        */


            }




    }
